package com.zp.viewpractice.BasePractice;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by izp on 2017/7/27.
 * 二阶贝塞尔曲线
 */
public class BezierTier2 extends View{
    private Paint mPaint;
    private Path mBezierPath;
    private int mCoordX,mCoordY;//坐标原点
    private PointF start,end,control;

    public BezierTier2(Context context) {
        super(context);
        init();
    }

    public BezierTier2(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setColor(Color.BLACK);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(8);
        mPaint.setTextSize(60);//文字文字的大小

        start = new PointF(0,0);
        end = new PointF(0,0);
        control = new PointF(0,0);

        mBezierPath = new Path();
    }

    /**
     * 获取的宽高比onMeasure准确
     * @param w
     * @param h
     * @param oldw
     * @param oldh
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mCoordX = w/2;
        mCoordY = h/2;
//        初始化数据点和控制点的位置
        start.x = mCoordX-200;
        start.y = mCoordY;
//        初始点（-200，0）

        end.x = mCoordX+200;
        end.y = mCoordY;
//        结束点（200，0）

        control.x = mCoordX;
        control.y = mCoordY-100;
//        控制点（0，100）
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
//        return super.onTouchEvent(event);
        control.x = event.getX();
        control.y = event.getY();
//        更新控制点的位置，然后重绘。
        invalidate();
        return true;//消费事件，不再传递？
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mBezierPath.reset();
//        绘制数据点和控制点
        mPaint.setColor(Color.GRAY);
        mPaint.setStrokeWidth(20);
        mPaint.setAntiAlias(true);

        canvas.drawPoint(start.x,start.y,mPaint);
        canvas.drawPoint(end.x,end.y,mPaint);
        canvas.drawPoint(control.x,control.y,mPaint);
//        绘制辅助线

        mPaint.setStrokeWidth(4);
        mPaint.setStyle(Paint.Style.STROKE);
        canvas.drawLine(start.x,start.y,control.x,control.y,mPaint);
        canvas.drawLine(end.x, end.y,control.x,control.y,mPaint);

//        绘制贝塞尔曲线
        mPaint.setColor(Color.CYAN);
        mPaint.setStrokeWidth(10);


        mBezierPath.moveTo(start.x,start.y);
        mBezierPath.quadTo(control.x,control.y,end.x,end.y);//从控制点到结束点
        canvas.drawPath(mBezierPath,mPaint);

    }
}
